﻿using Aliphant.Common;
using Aliphant.UI.Browser.Views;
using System.Text.RegularExpressions;

namespace Aliphant.UI.Browser.Managers
{
    public class TabManager : Singleton<TabManager>
    {
        private string defaultUrl;

        private IDictionary<string, WebView> Tabs = new Dictionary<string, WebView>();

        public event Action<WebView>? AddTabEvent;
        public event Action<WebView, int>? InsertTabEvent;
        public event Action<WebView>? RemoveTabEvent;
        public event Action<string>? UpdateInputUrlEvent;

        public int Selected { get; set; }


        public TabManager()
        {
            //if (ConfigContainer.Instance.cacheManager.Get("mainpage", out string du))
            //{
            //    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "web", du);
            //    if (File.Exists(path))
            //    {
            //        defaultUrl = "file:///" + path;
            //        return;
            //    }
            //}
            //defaultUrl = ResourceManager.Instance.MainPage;
            defaultUrl = "https://www.bing.com";
        }


        public void Init()
        {
            Create(defaultUrl);
        }

        public WebView? Get(string id)
        {
            if (Tabs.ContainsKey(id)) return Tabs[id];
            return null;
        }

        public List<WebView> GetAll()
        {
            return Tabs.Values.ToList();
        }

        public WebView Create(string url = "", int index = -1)
        {
            WebView webview = new WebView();

            if (!string.IsNullOrEmpty(url))
            {
                webview.webView.Source = new Uri(url);
                UpdateInputUrl(url);
            }

            Tabs.Add(webview.Id, webview);

            if (index == -1)
            {
                // 加到最后
                AddTabEvent?.Invoke(webview);
            }
            else
            {
                InsertTabEvent?.Invoke(webview, index);
            }

            return webview;
        }

        public void Remove(string id)
        {
            if (Tabs.ContainsKey(id))
            {
                var webview = Tabs[id];
                webview.webView.Dispose();

                Tabs.Remove(id);
                if (RemoveTabEvent != null)
                {
                    RemoveTabEvent.Invoke(webview);
                }

                webview = null;

                if (Tabs.Count == 0)
                {
                    Init();
                }
            }
        }

        public void UpdateInputUrl(string url)
        {
            if (UpdateInputUrlEvent != null)
                UpdateInputUrlEvent.Invoke(url);
        }

        public static string FormatUrl(string uri)
        {
            string pattern = @"^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?";
            string localPattern = @"^(https?:\/\/)?(localhost|127.0.0.1)?(:\d{1,5})?\/?$";

            if (Regex.IsMatch(uri, pattern))
            {
                if (!uri.StartsWith("http://") && !uri.StartsWith("https://") && !uri.StartsWith("file:///") && !uri.StartsWith("ftp://") && !uri.StartsWith("ftps://"))
                {
                    if (!uri.StartsWith("www."))
                    {
                        uri = "www." + uri;
                    }
                    uri = "https://" + uri;
                }
            }
            else if (Regex.IsMatch(uri, localPattern))
            {
                if (uri.Split(':').Length == 1)
                {
                    uri = uri + ":8080";
                }
            }
            else
            {
                uri = "https://www.baidu.com/s?ie=utf-8&wd=" + uri;
            }

            //if (!uri.StartsWith("http://") && !uri.StartsWith("https://"))
            //{
            //    if (!uri.StartsWith("www."))
            //    {
            //        uri = "www." + uri;
            //    }
            //    uri = "https://" + uri;
            //}
            return uri;
        }
    }
}
